package cn.cs.mathgo.gateway.config.filter;

import cn.cs.mathgo.app.entity.UserEntity;
import cn.cs.mathgo.common.constant.AuthConst;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class AuthHeaderFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        if (request.getMethod().equals("OPTIONS")) {
            return false;
        }else {
            return true;
        }
    }

    @Override
    public Object run() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        RequestContext requestContext = RequestContext.getCurrentContext();
        try {
            UserEntity principal = (UserEntity) authentication.getPrincipal();
            requestContext.addZuulRequestHeader(AuthConst.AUTH_USER,principal.getUsername());
            requestContext.addZuulRequestHeader(AuthConst.Auth_Id,principal.getId()+"");
        }catch (Exception e){
            return  null;
        }

        return null;
    }
}
